package com.venutech.gongan.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;

public class AddressUtils {
    /**
     * key值为 9405e0afbde5ff8ef9e11d162026d784 为高德地图申请类
     * 访问高德官网http
     * @param longitude 经度(02坐标系）
     * @param latitude 纬度（02坐标系）
     * http://restapi.amap.com/v3/geocode/regeo?key=XXX&s=rsv3&language=zh_cn&location=116.39,39.9&extensions=all&callback=&platform=JS
     * @return
     */
    public static Address getAddressByHttp(double longitude, double latitude) throws IOException {
        Address address = new Address();
        address.setLon(longitude);
        address.setLat(latitude);
        String url = "http://restapi.amap.com/v3/geocode/regeo?key=9405e0afbde5ff8ef9e11d162026d784&s=rsv3&language=zh_cn&extensions=all&callback=&platform=JS&location="+longitude+","+latitude;
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(10*000);
        client.getHttpConnectionManager().getParams().setSoTimeout(30*1000);
        GetMethod method = new GetMethod(url);
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("Method failed: " + method.getStatusLine());
        }
        byte[] responseBody = method.getResponseBody();
        String responseStr = new String(responseBody,"UTF-8");
        //System.out.println("返回值为"+responseStr);
        JSONObject parse = (JSONObject) JSONObject.parse(responseStr);
        JSONObject regeocode =  parse.getJSONObject("regeocode");
        //地址
        address.setAddress(regeocode.getString("formatted_address"));
        JSONArray roads = regeocode.getJSONArray("roads");
        if (Objects.nonNull(roads) && roads.size()>=2){
            JSONObject road1 = (JSONObject) roads.get(0);
            JSONObject road2 = (JSONObject) roads.get(1);
            address.setRoads(road1.getString("name")+"-"+road2.getString("name"));
        }
        JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
        if(Objects.nonNull(addressComponent)) {
            JSONObject streetNumber = addressComponent.getJSONObject("streetNumber");
            if(Objects.nonNull(streetNumber)) {
                address.setStreetAndNumber(streetNumber.getString("street") + "-" + streetNumber.getString("number"));
            }
            JSONObject building = addressComponent.getJSONObject("building");
            if(Objects.nonNull(building)) {
                String name = building.getString("name");
                if(!StringUtils.isEmpty(name) && !name.equals("[]")) {
                    address.setBuilding(name);
                }
            }
            String townCode = addressComponent.getString("towncode");
            if(!Strings.isBlank(townCode) && !townCode.equals("[]")) {
                address.setTownCode(townCode);
            }
            String townName = addressComponent.getString("township");
            if(!Strings.isBlank(townName) && !townName.equals("[]")) {
                address.setTownName(townName);
            }
            String districtCode = addressComponent.getString("adcode");
            if(!Strings.isBlank(districtCode) && !districtCode.equals("[]")) {
                address.setAreaCode(districtCode);
            }
            String districtName = addressComponent.getString("district");
            if(!Strings.isBlank(districtName) && !districtName.equals("[]")) {
                address.setAreaName(districtName);
            }
        }

        return address;
    }

    public static String getProvince(String lat, String log ) throws Exception {
        String urlString = "http://gc.ditu.aliyun.com/regeocoding?l="+lat+","+log+"&type=010";
        //String urlString = "http://restapi.amap.com/v3/geocode/regeo?key=9405e0afbde5ff8ef9e11d162026d784&s=rsv3&language=zh_cn&extensions=all&callback=&platform=JS&location="+log+","+lat;
        String res = "";
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                res += line+"\n";
            }
            in.close();
        } catch (Exception e) {
            System.out.println("error in wapaction,and e is " + e.getMessage());
        }
        return res;
    }

    public static void main(String[] args) throws Exception {
        String province = getProvince("31.337848","120.620689");
        JSONObject json =JSONObject.parseObject(province);
        System.out.println(json);

    }

}
